#!/bin/bash

# WordPress博客系统备份脚本
# 备份内容包括：MySQL数据库、WordPress文件

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m' # No Color

# 配置信息
BACKUP_DIR="/backup/blog"
DATE=$(date +%Y%m%d_%H%M%S)
MAX_BACKUPS=7  # 保留最近7天的备份

# 创建备份目录
mkdir -p $BACKUP_DIR

# 获取Kubernetes认证信息
KUBECONFIG="${KUBECONFIG:-$HOME/.kube/config}"

# 检查kubectl是否可用
if ! command -v kubectl &> /dev/null
then
    echo -e "${RED}错误: kubectl未安装或不可用${NC}"
    exit 1
fi

# 备份MySQL数据库
echo -e "${YELLOW}正在备份MySQL数据库...${NC}"
MYSQL_POD=$(kubectl get pods -n blog -l app=mysql -o jsonpath='{.items[0].metadata.name}')
if [ -z "$MYSQL_POD" ]; then
    echo -e "${RED}错误: 找不到MySQL Pod${NC}"
    exit 1
fi

# 获取数据库密码
MYSQL_PASSWORD=$(kubectl get secret -n blog mysql-secret -o jsonpath='{.data.password}' | base64 -d)

# 执行备份
kubectl exec -n blog $MYSQL_POD -- mysqldump -u wordpress -p"$MYSQL_PASSWORD" wordpress > $BACKUP_DIR/wordpress_db_$DATE.sql
if [ $? -ne 0 ]; then
    echo -e "${RED}错误: 数据库备份失败${NC}"
    exit 1
fi

# 备份WordPress文件
echo -e "${YELLOW}正在备份WordPress文件...${NC}"
WORDPRESS_POD=$(kubectl get pods -n blog -l app=wordpress -o jsonpath='{.items[0].metadata.name}')
if [ -z "$WORDPRESS_POD" ]; then
    echo -e "${RED}错误: 找不到WordPress Pod${NC}"
    exit 1
fi

# 创建临时tar文件
kubectl exec -n blog $WORDPRESS_POD -- tar -czf - -C /var/www html > $BACKUP_DIR/wordpress_files_$DATE.tar.gz
if [ $? -ne 0 ]; then
    echo -e "${RED}错误: WordPress文件备份失败${NC}"
    exit 1
fi

# 压缩备份文件
echo -e "${YELLOW}正在压缩备份文件...${NC}"
tar -czf $BACKUP_DIR/blog_backup_$DATE.tar.gz -C $BACKUP_DIR wordpress_db_$DATE.sql wordpress_files_$DATE.tar.gz
if [ $? -ne 0 ]; then
    echo -e "${RED}错误: 压缩备份文件失败${NC}"
    exit 1
fi

# 删除临时文件
rm -f $BACKUP_DIR/wordpress_db_$DATE.sql $BACKUP_DIR/wordpress_files_$DATE.tar.gz

# 清理旧备份
echo -e "${YELLOW}清理旧备份...${NC}"
find $BACKUP_DIR -name "blog_backup_*.tar.gz" -type f -mtime +$MAX_BACKUPS -delete

echo -e "${GREEN}备份完成！${NC}"
echo -e "${GREEN}备份文件位置: $BACKUP_DIR/blog_backup_$DATE.tar.gz${NC}"